package com.zy.nettypoject.netty.nio_thread;

import io.netty.buffer.ByteBuf;

import javax.annotation.security.RunAs;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class ServerThreadNio {
    public static void main(String[] args) throws Exception {
        Thread.currentThread().setName("多线程测试nio");
        //开启一个选择器
        Selector selector = Selector.open();
        ServerSocketChannel sc = ServerSocketChannel.open();
        sc.configureBlocking(false);
        sc.bind(new InetSocketAddress(8099));
        //监听请求事件
        sc.register(selector, SelectionKey.OP_ACCEPT);

        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    //建立work处理链接


//                    ServerSocketChannel channel =(ServerSocketChannel) key.channel();
//                    SocketChannel accept = channel.accept();
//                    accept.configureBlocking(false);
//                    //添加附件
//                    ByteBuffer allocate = ByteBuffer.allocate(16);
//                    accept.register(selector,SelectionKey.OP_READ,allocate);
                }
            }
        }
    }

    class Work implements Runnable {
        private Thread thread;
        private  Selector selector;
        /**
         * 名字区分
         */
        private String name;

        public Work(String name){
            this.name = name;
        }
        public void register() throws IOException {
            selector = Selector.open();
            thread = new Thread(this, name);
            thread.start();
        }
        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey next = iterator.next();
                        if (next.isReadable()) {
                            ByteBuffer allocate = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) next.channel();
                            channel.read(allocate);
                            allocate.flip();
                            System.out.println(Charset.defaultCharset().decode(allocate));
                        }
                    }
                } catch (IOException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
